package com.fzu.geometa.metadata.util;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.util.List;

public class XmlUtilsOld {
    private static final SAXReader sax = new SAXReader();

    public static boolean saveDocument(Document doc, String savePath) {

        //设置输出格式
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setEncoding("UTF-8");
        outputFormat.setIndent(true);
        outputFormat.setIndentSize(4);

        OutputStream outputStream = null;
        XMLWriter xmlWriter = null;

        try {
            outputStream = new FileOutputStream(savePath);
            xmlWriter = new XMLWriter(outputStream, outputFormat);
            xmlWriter.write(doc);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (xmlWriter != null) {
                    xmlWriter.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return true;
    }

    public static Document readXmlFile(String filePath) throws DocumentException {
        return sax.read(new File(filePath));
    }

    public static Document readXmlStr(String xmlStr) throws DocumentException {
        return DocumentHelper.parseText(xmlStr);
    }


    public static void verify(Document doc1, Document doc2) {
        if (doc1 == null && doc2 == null) {
            return;
        }
        System.out.println("Start validation...");
        getNodes(doc1.getRootElement(), doc2.getRootElement());
        System.out.println("finished");

    }

    private static void getNodes(Element node1, Element node2) {
        //元素名称不一致
        if (!node1.getQualifiedName().equals(node2.getQualifiedName())) {
            System.out.println("Path1:"+node1.getPath());
            System.out.println("Path2:"+node2.getPath());
            throw new RuntimeException("Wrong name: \"" + node1.getQualifiedName() + "\" - \"" + node2.getQualifiedName()+"\"");
        }
        //元素文本值不同
        if (!node1.getTextTrim().equals(node2.getTextTrim())) {
            System.out.println("Path1:"+node1.getPath());
            System.out.println("Path2:"+node2.getPath());
            throw new RuntimeException("Wrong text: \"" + node1.getTextTrim() + "\" - \"" + node2.getTextTrim()+"\"");
        }

        List<Attribute> listAttr1 = node1.attributes();//当前节点的所有属性的list
        List<Attribute> listAttr2 = node2.attributes();
        //属性数量不一致
        if (listAttr1.size() != listAttr2.size()) {
            System.out.println("Path1:"+node1.getPath());
            System.out.println("Path2:"+node2.getPath());
            throw new RuntimeException("The number of attributes is different");
        }

        for (int i = 0; i < listAttr1.size(); i++) {
            Attribute attribute1 = listAttr1.get(i);
            Attribute attribute2=null;
            boolean tag=false;
            for (int j = 0; j < listAttr2.size(); j++) {
                if (listAttr2.get(j).getName().equals(attribute1.getName())){
                    tag=true;
                    attribute2=listAttr2.get(j);
                    break;
                }
            }
            //属性名称不一致
            if (!tag) {
                System.out.println("Path1:"+node1.getPath());
                System.out.println("Path2:"+node2.getPath());
                throw new RuntimeException("Attribute name : \"" + attribute1.getName() + "\" does not exist in document 2.");
            }
            //属性值不一样
            if (!attribute1.getValue().equals(attribute2.getValue())) {
                System.out.println("Path1:"+node1.getPath());
                System.out.println("Path2:"+node2.getPath());
                throw new RuntimeException("Wrong attribute value: \"" + attribute1.getValue() + "\" - \"" + attribute2.getValue()+"\"");
            }
        }
        List<Element> listElement1 = node1.elements();
        List<Element> listElement2 = node2.elements();
        //下级元素数量不一致
        if (listElement1.size() != listElement2.size()) {
            System.out.println("Path1:"+node1.getPath());
            System.out.println("Path2:"+node2.getPath());
            throw new RuntimeException("The number of elements is different");
        }

        for (int i = 0; i < listElement1.size(); i++) {
            getNodes(listElement1.get(i), listElement2.get(i));
        }
    }
    /***
     * 格式化xml为string
     * @param document
     * @return
     */
    public static String prettyString(Document document) {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setNewLineAfterDeclaration(false);
        return xmlDocToStr(document, format);
    }

    public static String compactString(Document document) {
        OutputFormat format = OutputFormat.createCompactFormat();
        return xmlDocToStr(document, format);
    }

    private static String xmlDocToStr(Document document, OutputFormat format) {
        format.setEncoding(document.getXMLEncoding());
        StringWriter stringWriter = new StringWriter();
        XMLWriter writer = new XMLWriter(stringWriter, format);
        try {
            writer.write(document);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringWriter.toString();
    }

    private XmlUtilsOld() {};
}
